/**
 * 本地数据存储服务
 * 用于管理编组和设备的操作数据
 * 这是小程序中唯一的存储服务提供者，所有存储操作都应通过此模块进行
 */

// const { logger } = require('../utils/logger') // 修改导入方式
const loggerUtil = require('../utils/logger')
// console.log('--- Debugging loggerUtil at module top ---', loggerUtil); // <-- 移除调试
const logger = loggerUtil.logger
// console.log('--- Debugging logger at module top ---', logger); // <-- 移除调试
// console.log('--- Type of logger.log at module top ---', typeof logger?.log); // <-- 移除调试

// 存储键名前缀
const STORAGE_KEYS = {
  OPENID: "openid1",
  SID: "sid",
  DEVICEIDS: "deviceIds",
  DEVICE: {
    DEVICE: "device",
    CH: "ch",
    TEMP: "temp",
    AUTORUN: "autoRun",
    TEMP_SYNC: "tmp_sync",
    SCHEDULE: "schedule",
    AUTO: "auto",
    HAND: "hand",
    UPDOWN: "updown",
  },

  // 模式设置页数据
  MODE_SETTING: {
    BUTTON_DATA: 'modeSettingButtonData',
    CHANNEL_CONFIGS: 'channelConfigs',
    TEMP_SWITCH: 'tempSwitchSettings',
    COOLING: 'coolingSettings',
    CONFIG_DATA: 'configData',
  },
  // 快捷模式页数据
  SHORTCUT_MODE: {
    CURRENT_INDEX: 'shortcutModeCurrentIndex',
    MODE_SETTINGS: 'shortcutModeSettings',
    FIRST_VISIT: 'shortcutModeFirstVisit',
  },
  // 玩家模式页数据
  PLAYER_MODE: {
    PRESETS: 'playerModePresets',
    FIRST_VISIT: 'playerModeFirstVisit',
  },
  // 灯光模式状态（自动/手动）
  LIGHT_MODE_STATE: 'lightModeState',

  // 高阶模式页数据
  ADVANCED_MODE: {
    CURVES: 'advancedModeCurves',
  },
  GROUPIDS: 'groupIds',

  //最后一次手动调整灯光配置
  LAST_MANUAL_VAL: 'lastManualVal',

  SAVED_CONFIGS: 'saved_configs',

  REFRESH_DEVICED_FLAG: 'refresh_devices_flag',

  TIMER_TASKS: 'timerTasks',

  ACTIVE_IDS: 'activeIds',

  IOS_GUIDE_SHOW: 'iosGuideShow',


}

// 存储键名前缀
const STORAGE_SAVE_KEYS = [
  //OPENID: "openid1",
  //SID: "sid",
  //DEVICEIDS,
  STORAGE_KEYS.DEVICE.DEVICE,
  STORAGE_KEYS.DEVICE.CH,
  STORAGE_KEYS.DEVICE.TEMP,
  STORAGE_KEYS.DEVICE.AUTORUN,
  STORAGE_KEYS.DEVICE.TEMP_SYNC,
  //STORAGE_KEYS.DEVICE.SCHEDULE,
  STORAGE_KEYS.DEVICE.AUTO,
  STORAGE_KEYS.DEVICE.HAND,
  STORAGE_KEYS.DEVICE.UPDOWN,

  // 模式设置页数据
  STORAGE_KEYS.MODE_SETTING.BUTTON_DATA,
  STORAGE_KEYS.MODE_SETTING.CHANNEL_CONFIGS,
  STORAGE_KEYS.MODE_SETTING.TEMP_SWITCH,
  STORAGE_KEYS.MODE_SETTING.COOLING,
  STORAGE_KEYS.MODE_SETTING.CONFIG_DATA,

  // 快捷模式页数据
  STORAGE_KEYS.SHORTCUT_MODE.CURRENT_INDEX,
  STORAGE_KEYS.SHORTCUT_MODE.MODE_SETTINGS,
  STORAGE_KEYS.SHORTCUT_MODE.FIRST_VISIT,
  // 玩家模式页数据
  STORAGE_KEYS.PLAYER_MODE.PRESETS,
  STORAGE_KEYS.PLAYER_MODE.FIRST_VISIT,
  // 灯光模式状态（自动/手动）
  //STORAGE_KEYS.LIGHT_MODE_STATE: 'lightModeState',

  // 高阶模式页数据
  STORAGE_KEYS.ADVANCED_MODE.CURVES,
  //GROUPS: 'groups',

  //最后一次手动调整灯光配置
  //LAST_MANUAL_VAL: 'lastManualVal',

  //SAVED_CONFIGS:'saved_configs',

  STORAGE_KEYS.TIMER_TASKS,
]

// 删除键名前缀
const STORAGE_DEL_KEYS = [
  //OPENID: "openid1",
  //SID: "sid",
  //DEVICEIDS,
  STORAGE_KEYS.DEVICE.DEVICE,
  STORAGE_KEYS.DEVICE.CH,
  STORAGE_KEYS.DEVICE.TEMP,
  STORAGE_KEYS.DEVICE.AUTORUN,
  STORAGE_KEYS.DEVICE.TEMP_SYNC,
  STORAGE_KEYS.DEVICE.SCHEDULE,
  STORAGE_KEYS.DEVICE.AUTO,
  STORAGE_KEYS.DEVICE.HAND,
  STORAGE_KEYS.DEVICE.UPDOWN,

  // 模式设置页数据
  STORAGE_KEYS.MODE_SETTING.BUTTON_DATA,
  STORAGE_KEYS.MODE_SETTING.CHANNEL_CONFIGS,
  STORAGE_KEYS.MODE_SETTING.TEMP_SWITCH,
  STORAGE_KEYS.MODE_SETTING.COOLING,
  STORAGE_KEYS.MODE_SETTING.CONFIG_DATA,

  // 快捷模式页数据
  STORAGE_KEYS.SHORTCUT_MODE.CURRENT_INDEX,
  STORAGE_KEYS.SHORTCUT_MODE.MODE_SETTINGS,
  STORAGE_KEYS.SHORTCUT_MODE.FIRST_VISIT,
  // 玩家模式页数据
  STORAGE_KEYS.PLAYER_MODE.PRESETS,
  STORAGE_KEYS.PLAYER_MODE.FIRST_VISIT,
  // 灯光模式状态（自动/手动）
  STORAGE_KEYS.LIGHT_MODE_STATE,

  // 高阶模式页数据
  STORAGE_KEYS.ADVANCED_MODE.CURVES,

  //最后一次手动调整灯光配置
  STORAGE_KEYS.LAST_MANUAL_VAL,

  STORAGE_KEYS.SAVED_CONFIGS,

  STORAGE_KEYS.TIMER_TASKS,
]

/**
 * 获取存储键名
 * @param {string} keyType - 存储键类型
 * @param {string} id - 设备ID或编组ID
 * @returns {string} 完整的存储键名
 */
function getStorageKey(keyType, id) {
  // 如果是设备/编组列表，直接返回键名
  const typePrefix = 'key_'
  if (keyType === STORAGE_KEYS.OPENID || keyType === STORAGE_KEYS.SID || keyType === STORAGE_KEYS.DEVICEIDS || keyType === STORAGE_KEYS.GROUPIDS || keyType === STORAGE_KEYS.REFRESH_DEVICED_FLAG || keyType === STORAGE_KEYS.ACTIVE_IDS || keyType === STORAGE_KEYS.IOS_GUIDE_SHOW) {
    return typePrefix + keyType
  }

  // 确保id是有效的
  if (!id) {
    console.error('getStorageKey: 无效的ID', keyType)
    id = 'unknown'
  }
  // 记录生成的键名，帮助调试
  const key = `${typePrefix}${keyType}_${id}`
  return key
}

/**
 * 保存数据到本地存储
 * @param {string} key - 存储键名
 * @param {any} data - 要保存的数据
 */
function saveData(key, data) {
  try {
    if (!key) {
      console.error('保存数据失败: 未提供key')
      return false
    }

    // 检查数据类型，确保数组和对象在序列化前是正确的类型
    if (data !== null && typeof data === 'object') {
      // 如果键名包含特定标识，强制类型检查
      if (key.includes('TimerTasks') && !Array.isArray(data)) {
        logger.error(`保存数据失败: 键 ${key} 期望保存数组，但得到 ${typeof data}，尝试转换`);
        // 尝试将对象转换为数组（如果可能）
        if (Object.keys(data).length === 0) {
          // 空对象转换为空数组
          data = [];
          logger.warn(`已将空对象转换为空数组并保存到 ${key}`);
        } else {
          // 如果对象有数据且不是数组，记录错误但仍尝试保存
          logger.error(`无法将非空对象转换为数组: ${JSON.stringify(data).substring(0, 100)}`);
          return false;
        }
      }
    }

    // 对象类型数据转为JSON字符串
    const value = typeof data === 'object' ? JSON.stringify(data) : data
    wx.setStorageSync(key, value)
    // console.log(`数据已保存: ${key}`) // 移除调试
    return true
  } catch (e) {
    logger.error(`保存数据失败: ${key}`, e)
    return false
  }
}

/**
 * 从本地存储获取数据
 * @param {string} key - 存储键名
 * @param {boolean} parseJson - 是否解析JSON
 * @param {any} defaultValue - 解析失败时的默认值
 * @returns {any} 获取的数据
 */
function getData(key, parseJson = true, defaultValue = null) {
  try {
    if (!key) {
      console.error('获取数据失败: 未提供key')
      return defaultValue
    }
    const value = wx.getStorageSync(key)

    // 处理空值情况
    if (value === undefined || value === null || value === '') {
      return defaultValue
    }

    // 处理字符串类型的JSON解析
    if (parseJson && typeof value === 'string') {
      // 确保字符串不为空且是有效的JSON格式
      const trimmedValue = value.trim()
      if (trimmedValue === '') {
        // 空字符串情况下返回默认值
        logger.warn(`存储键 ${key} 的值为空字符串`)
        return defaultValue
      }

      try {
        const parsedValue = JSON.parse(trimmedValue)

        // 检查类型匹配 - 如果默认值是数组但解析结果不是，则使用默认值
        if (Array.isArray(defaultValue) && !Array.isArray(parsedValue)) {
          logger.warn(`存储键 ${key} 应该是数组，但实际是 ${typeof parsedValue}，使用默认值`)
          return defaultValue
        }

        // 检查数据结构类型 - 如果键名包含TimerTasks且应该是数组
        if (key.includes('TimerTasks') && !Array.isArray(parsedValue)) {
          logger.warn(`存储键 ${key} 期望是数组但实际是 ${typeof parsedValue}，将使用空数组替代`)
          // 自动修复存储
          if (typeof parsedValue === 'object' && Object.keys(parsedValue).length === 0) {
            saveData(key, []);
            logger.info(`已自动修复存储键 ${key} 的空对象为空数组`);
          }
          return [];
        }

        return parsedValue
      } catch (e) {
        logger.error(`解析JSON数据失败: ${key}`, {
          error: e,
          data: value
        })
        // 如果是数组或对象类型的默认值，则返回默认值
        if (
          defaultValue !== null &&
          (Array.isArray(defaultValue) || typeof defaultValue === 'object')
        ) {
          return defaultValue
        }
        return value
      }
    }

    return value
  } catch (e) {
    logger.error(`获取数据失败: ${key}`, {
      error: e
    })
    return defaultValue
  }
}

/**
 * 获取设备列表
 * @returns {Array} 设备列表
 */
/*function getDevices() {
  const devices = getData(STORAGE_KEYS.DEVICES, true, [])
  return devices.map(device => {
   
    return device
  })
}*/

/**
 * 保存设备列表
 * @param {Array} devices - 设备列表
 * @returns {boolean} 是否保存成功
 */
/*function saveDevices(devices) {
  // 确保devices是数组
  if (!Array.isArray(devices)) {
    logger.error('保存的设备数据不是数组:', devices)
    devices = Array.isArray(devices) ? devices : []
  }
  return saveData(STORAGE_KEYS.DEVICES, devices)
}*/

/**
 * 获取编组列表
 * @returns {Array} 编组列表
 */
function getGroups() {
  const groups = []
  const ids = getGroupIds()
  ids.forEach(id => {
    const device = getDeviceInfo(id)
    if (device) {
      groups.push(device)
    }
  })
  return groups;
}

/**
 * 获取设备或编组的模式设置数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object} 模式设置数据
 */
function getModeSettingData(id) {
  const buttonDataKey = getStorageKey(STORAGE_KEYS.MODE_SETTING.BUTTON_DATA, id)
  const channelConfigsKey = getStorageKey(STORAGE_KEYS.MODE_SETTING.CHANNEL_CONFIGS, id)
  const tempSwitchKey = getStorageKey(STORAGE_KEYS.MODE_SETTING.TEMP_SWITCH, id)
  const coolingKey = getStorageKey(STORAGE_KEYS.MODE_SETTING.COOLING, id)

  return {
    buttonData: getData(buttonDataKey, true, null), // 假设按钮数据是对象
    channelConfigs: getData(channelConfigsKey, true, []), // 为通道配置提供空数组作为默认值
    tempSwitchSettings: getData(tempSwitchKey, true, null), // 假设临时开关设置是对象
    coolingSettings: getData(coolingKey, true, null), // 假设散热设置是对象
  }
}

/**
 * 保存设备或编组的模式设置数据
 * @param {string} id - 设备ID或编组ID
 * @param {Object} data - 模式设置数据
 */
function saveModeSettingData(id, data) {
  const {
    buttonData,
    channelConfigs,
    tempSwitchSettings,
    coolingSettings
  } = data

  if (buttonData) {
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.BUTTON_DATA, id)
    saveData(key, buttonData)
  }

  if (channelConfigs) {
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.CHANNEL_CONFIGS)
    saveData(key, channelConfigs)
  }

  if (tempSwitchSettings) {
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.TEMP_SWITCH, id)
    saveData(key, tempSwitchSettings)
  }

  if (coolingSettings) {
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.COOLING, id)
    saveData(key, coolingSettings)
  }
}

/**
 * 获取设备或编组的快捷模式数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object} 快捷模式数据
 */
function getShortcutModeData(id) {

  const currentIndexKey = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.CURRENT_INDEX, id)
  const modeSettingsKey = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.MODE_SETTINGS, id)
  const timerTasksKey = getStorageKey(STORAGE_KEYS.TIMER_TASKS, id)
  const firstVisitKey = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.FIRST_VISIT, id)

  // 特别处理timerTasks数据，确保返回的始终是数组
  let timerTasks;
  try {
    // 直接从getData获取，已经有类型检查机制
    timerTasks = getData(timerTasksKey, true, []);

    // 额外保证是数组类型
    if (!Array.isArray(timerTasks)) {
      logger.error(`getShortcutModeData: timerTasks不是数组类型，实际是 ${typeof timerTasks}，将重置为空数组`);

      // 如果是空对象，转换为空数组且保存回存储
      if (typeof timerTasks === 'object' && Object.keys(timerTasks).length === 0) {
        logger.warn(`将空对象timerTasks重置为空数组并保存`);
        saveData(timerTasksKey, []);
      }

      timerTasks = [];
    }
  } catch (e) {
    logger.error(`获取timerTasks数据异常:`, e);
    timerTasks = [];
  }

  return {
    currentIndex: getData(currentIndexKey, false, 0),
    modeSettings: getData(modeSettingsKey, true, null), // Default to null to check validity later
    timerTasks: timerTasks, // 使用经过严格检查的timerTasks
    firstVisit: getData(firstVisitKey, false, true), // Default to true for first visit
  }
}

/**
 * 保存设备或编组的快捷模式数据
 * @param {string} id - 设备ID或编组ID
 * @param {Object} data - 快捷模式数据
 */
function saveShortcutModeData(id, data) {
  const {
    currentIndex,
    modeSettings,
    timerTasks
  } = data

  if (currentIndex !== undefined) {
    const key = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.CURRENT_INDEX, id)
    saveData(key, currentIndex)
  }
  if (modeSettings) {
    const key = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.MODE_SETTINGS, id)
    saveData(key, modeSettings)
  }
  if (timerTasks) {
    const key = getStorageKey(STORAGE_KEYS.TIMER_TASKS, id)
    saveData(key, timerTasks)
  }
}

/**
 * 获取设备或编组的玩家模式数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object} 玩家模式数据
 */
function getPlayerModeData(id) {
  const presetsKey = getStorageKey(STORAGE_KEYS.PLAYER_MODE.PRESETS, id)
  const timerTasksKey = getStorageKey(STORAGE_KEYS.TIMER_TASKS, id)
  const firstVisitKey = getStorageKey(STORAGE_KEYS.PLAYER_MODE.FIRST_VISIT, id)
  let presets = getData(presetsKey, true, []);
  // 特别处理timerTasks数据，确保返回的始终是数组
  let timerTasks;
  try {
    // 直接从getData获取，已经有类型检查机制
    timerTasks = getData(timerTasksKey, true, []);

    // 额外保证是数组类型
    if (!Array.isArray(timerTasks)) {
      logger.error(`getPlayerModeData: timerTasks不是数组类型，实际是 ${typeof timerTasks}，将重置为空数组`);

      // 如果是空对象，转换为空数组且保存回存储
      if (typeof timerTasks === 'object' && Object.keys(timerTasks).length === 0) {
        logger.warn(`将空对象timerTasks重置为空数组并保存`);
        saveData(timerTasksKey, []);
      }

      timerTasks = [];
    }
  } catch (e) {
    logger.error(`获取timerTasks数据异常:`, e);
    timerTasks = [];
  }

  return {
    presets: presets,
    timerTasks: timerTasks, // 使用经过严格检查的timerTasks
    firstVisit: getData(firstVisitKey, false, true), // Default to true for first visit
  }
}

/**
 * 获取设备或编组的玩家模式数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object} 玩家模式数据
 */
function getPlayerModePresets(id) {
  const presetsKey = getStorageKey(STORAGE_KEYS.PLAYER_MODE.PRESETS, id)
  return getData(presetsKey, true, [])
}

/**
 * 保存设备或编组的玩家模式数据
 * @param {string} id - 设备ID或编组ID
 * @param {Object} data - 玩家模式数据
 */
function savePlayerModeData(id, data) {
  const {
    presets,
    timerTasks
  } = data

  if (presets) {
    const key = getStorageKey(STORAGE_KEYS.PLAYER_MODE.PRESETS, id)
    saveData(key, presets)
  }

  if (timerTasks) {
    const key = getStorageKey(STORAGE_KEYS.TIMER_TASKS, id)
    saveData(key, timerTasks)
  }
}

/**
 * 获取设备或编组的高阶模式数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object} 高阶模式数据
 */
function getAdvancedModeData(id) {
  const curvesKey = getStorageKey(STORAGE_KEYS.ADVANCED_MODE.CURVES, id)
  return {
    curves: getData(curvesKey, true, null), // 假设曲线是对象或数组
  }
}

/**
 * 保存设备或编组的高阶模式数据
 * @param {string} id - 设备ID或编组ID
 * @param {Object} data - 高阶模式数据
 */
function saveAdvancedModeData(id, data) {
  const {
    curves
  } = data

  if (curves) {
    const key = getStorageKey(STORAGE_KEYS.ADVANCED_MODE.CURVES, id)
    saveData(key, curves)
  }
}

/**
 * 设备加入编组时同步数据
 * @param {string} deviceId - 设备ID
 * @param {string} groupId - 编组ID
 */
function syncDeviceDataFromGroup(deviceId, groupId) {
  if (!deviceId || !groupId) {
    logger.error('syncDeviceDataFromGroup: 无效的设备ID或编组ID')
    return false
  }

  const device = getDeviceInfo(deviceId)
  if (device != null) {
    device.inGroup = true
    device.groupId = groupId
    saveDeviceInfo(deviceId, device)
  }
}

/**
 * 清除设备与编组的同步状态和数据
 * @param {string} deviceId - 设备ID
 */
function clearDeviceGroupSyncData(deviceId) {
  if (!deviceId) {
    logger.error('clearDeviceGroupSyncData: 无效的设备ID')
    return false
  }

  const device = getDeviceInfo(deviceId)
  if (device != null) {
    device.inGroup = false
    device.groupId = null
    saveDeviceInfo(deviceId, device)
  }
  return true
}

/**
 * 删除编组时恢复设备状态
 * @param {string} groupId - 编组ID
 */
function restoreDevicesOnGroupDelete(groupId) {
  if (!groupId) {
    logger.error('restoreDevicesOnGroupDelete: 无效的编组ID')
    return false
  }

  const localGroupIds = getGroupIds()
  const groupIndex = localGroupIds.findIndex(id => id === groupId)

  if (groupIndex === -1) {
    logger.warn(`restoreDevicesOnGroupDelete: 未找到编组 ${groupId}，可能已被删除`)
    return true // Consider success if group doesn't exist
  }

  const group = getDeviceInfo(groupId)
  const deviceIds = Array.isArray(group.deviceIds) ? group.deviceIds : []
  let allDevicesRestored = true

  // 遍历编组中的设备，清除它们的编组状态
  deviceIds.forEach(deviceId => {
    const success = clearDeviceGroupSyncData(deviceId) // Call clearDeviceGroupSyncData for each device
    if (!success) {
      allDevicesRestored = false
      logger.error(`restoreDevicesOnGroupDelete: 恢复设备 ${deviceId} 状态失败`)
      // Continue trying to restore other devices
    }
  })

  if (!allDevicesRestored) {
    logger.warn(`restoreDevicesOnGroupDelete: 并非所有编组 ${groupId} 内的设备都成功恢复状态`)
    // Decide if this constitutes overall failure
  }

  // 从编组列表中移除该编组
  localGroupIds.splice(groupIndex, 1)

  // 保存更新后的编组列表
  saveGroupIds(localGroupIds)

  removeDevice(groupId) //删除设备和组通用

  logger.info(`编组 ${groupId} 已删除，其内部设备状态已恢复（解除关联）`) // log -> info
  return allDevicesRestored // Return status based on whether all devices were processed
}

/**
 * 检查是否是首次访问快捷模式页面
 * @param {string} id - 设备ID或编组ID
 * @returns {boolean} 是否是首次访问
 */
function isFirstVisitShortcutMode(id) {
  const key = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.FIRST_VISIT, id)
  return getData(key, false, true)
}

/**
 * 设置快捷模式页面已访问标记
 * @param {string} id - 设备ID或编组ID
 */
function setShortcutModeVisited(id) {
  const key = getStorageKey(STORAGE_KEYS.SHORTCUT_MODE.FIRST_VISIT, id)
  saveData(key, false)
}

/**
 * 检查是否是首次访问玩家模式页面
 * @param {string} id - 设备ID或编组ID
 * @returns {boolean} 是否是首次访问
 */
function isFirstVisitPlayerMode(id) {
  const key = getStorageKey(STORAGE_KEYS.PLAYER_MODE.FIRST_VISIT, id)
  return getData(key, false, true)
}

/**
 * 设置玩家模式页面已访问标记
 * @param {string} id - 设备ID或编组ID
 */
function setPlayerModeVisited(id) {
  const key = getStorageKey(STORAGE_KEYS.PLAYER_MODE.FIRST_VISIT, id)
  saveData(key, false)
}

/**
 * 获取灯光模式状态（自动/手动）
 * @param {string} id - 设备ID或编组ID
 * @returns {string} 灯光模式状态，'auto'表示自动模式，'manual'表示手动模式
 */
function getLightModeState(id) {
  const key = getStorageKey(STORAGE_KEYS.LIGHT_MODE_STATE, id)
  return getData(key, false, 'manual') // 默认为手动模式
}

/**
 * 保存灯光模式状态（自动/手动）
 * @param {string} id - 设备ID或编组ID
 * @param {string} state - 灯光模式状态，'auto'表示自动模式，'manual'表示手动模式
 */
function saveLightModeState(id, state) {
  const key = getStorageKey(STORAGE_KEYS.LIGHT_MODE_STATE, id)
  saveData(key, state)
}

/**
 * 获取灯光模式状态（自动/手动）
 * @param {string} id - 设备ID或编组ID
 * @returns {string} 灯光模式状态，'auto'表示自动模式，'manual'表示手动模式
 */
function isManualModeState(id) {
  const mode = getLightModeState(id)
  return "auto" !== mode
}

/**
 * 保存设备配置数据
 * @param {string} id - 设备ID或编组ID
 * @param {Object} configData - 设备配置数据
 * @returns {boolean} 是否保存成功
 */
function saveDeviceConfig(id, configData) {
  try {
    // 构建存储键
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.CONFIG_DATA, id)

    // 保存配置数据
    return saveData(key, configData)
  } catch (e) {
    logger.error(`保存设备配置数据失败: ${id}`, e)
    return false
  }
}

/**
 * 获取设备配置数据
 * @param {string} id - 设备ID或编组ID
 * @returns {Object|null} 设备配置数据或null
 */
function getDeviceConfig(id) {
  try {
    // 构建存储键
    const key = getStorageKey(STORAGE_KEYS.MODE_SETTING.CONFIG_DATA, id)

    // 获取配置数据，默认为null
    return getData(key, true, null)
  } catch (e) {
    logger.error(`获取设备配置数据失败: ${id}`, e)
    return null
  }
}

/**
 * 保存最后一次手动调整灯光配置
 * @param {string} id 设备id
 * @param {array} valArr 通道信息
 */
function saveLastManualVal(id, valArr) {
  if (!valArr || !Array.isArray(valArr)) {
    return;
  }
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.LAST_MANUAL_VAL, id)
  saveData(key, valArr)
}

/**
 * 获取最后一次手动调整灯光配置
 * @param {string} id 设备id
 * @return 灯光配置
 */
function getLastManualVal(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.LAST_MANUAL_VAL, id)
  return getData(key, true, [])
}

/**
 * 获取设备列表
 * @returns {Array} 设备列表
 */
function getDeviceIds() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICEIDS)
  const deviceIds = getData(key, true, [])
  const newIds = []
  let flg = false
  deviceIds.forEach(id => {
    if (id != null) {
      newIds.push(id)
    } else {
      flg = true
    }
  })
  if (flg) {
    saveDeviceIds(newIds)
  }

  return newIds
}

/**
 * 保存设备ids列表
 */
function saveDeviceIds(ids) {
  const key = getStorageKey(STORAGE_KEYS.DEVICEIDS)
  saveData(key, ids)
}

/**
 * 获取设备信息
 * @param {string}} id 设备id
 */
function getDeviceInfo(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.DEVICE, id)
  const device = getData(key, true, null)
  return device
}

/**
 * 保存设备信息
 * @param {string}} id 设备id
 * @param {object}} deviceInfo 设备信息
 */
function saveDeviceInfo(id, deviceInfo) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.DEVICE, id)
  saveData(key, deviceInfo)
}

/**
 * 批量获取设备信息
 * @param {array}} ids 设备ids
 */
function batchGetDeviceInfo(ids) {
  const keys = []
  ids.forEach(id => {
    keys.push(getStorageKey(STORAGE_KEYS.DEVICE.DEVICE, id))
  })
  if (keys.length == 0) {
    return keys
  }

  const values = wx.batchGetStorageSync(keys) || []
  const devices = []
  for (let i = 0; i < values.length; i++) {
    const value = values[i]
    if (value === undefined || value === null || value === '') {
      continue
    }
    if (typeof value === "object") {
      devices.push(value)
    } else {
      const trimmedValue = value.trim()
      if (trimmedValue === '') {
        // 空字符串情况下返回默认值
        logger.warn(`存储键 ${key} 的值为空字符串`)
        continue
      }
      const parsedValue = JSON.parse(trimmedValue)
      devices.push(parsedValue)
    }
  }

  return devices
}

/**
 * 获取设备通道信息
 * @param {string}} id 设备id
 */
function getDeviceChannels(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.CH, id)
  const channels = getData(key, true, [])
  return channels
}

/**
 * 保存通道信息
 * @param {string} id 设备id
 * @param {array} channels 通道信息
 */
function saveDeviceChannels(id, channels) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.CH, id)
  saveData(key, channels)
}

/**
 * 保存温度信息
 * @param {string} id 设备id
 * @param {object} tempInfo 温度信息
 */
function saveTempInfo(id, tempInfo) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.TEMP, id)
  saveData(key, tempInfo)
}

/**
 * 获取温度信息
 * @param {string} id 设备id
 * @param {object} tempInfo 温度信息
 */
function getTempInfo(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.TEMP, id)
  const data = getData(key, true, {
    fanStartTemp: 40,
    ntcDiffTemp: 0
  })
  return data
}

/**
 * 设置临时开关灯配置已同步到设备
 * @param {string} id 设备id
 */
function setTmpSynced(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.TEMP_SYNC, id)
  saveData(key, "1")
}

/**
 * 设置临时开关灯配置已同步到设备
 * @param {string} id 设备id
 */
function getTmpSynced(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.TEMP_SYNC, id)
  return getData(key, false, "")
}

/**
 * 保存当前行程信息
 * @param {string} id 设备id
 * @param {object} scheduleInfo 温度信息
 */
function saveScheduleInfo(id, scheduleInfo) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.SCHEDULE, id)
  saveData(key, scheduleInfo)
}

/**
 * 获取当前行程信息
 * @param {string} id 设备id
 */
function getScheduleInfo(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.SCHEDULE, id)
  const data = getData(key, true, null)
  return data
}

/**
 * 移除当前行程信息
 * @param {string} id 设备id
 */
function removeScheduleInfo(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.SCHEDULE, id)
  wx.removeStorageSync(key)
}

/**
 * 设置openid
 * @param {string} openid openid
 */
function setOpenid(openid) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.OPENID)
  saveData(key, openid)
}

/**
 * 获取openid
 */
function getOpenid() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.OPENID)
  const data = getData(key, false, null)
  return data
}

/**
 * 设置sid
 * @param {string} sid sid
 */
function setSid(sid) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.SID)
  saveData(key, sid)
}

/**
 * 获取sid
 */
function getSid() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.SID)
  const data = getData(key, false, null)
  return data
}

/**
 * 保存运行状态信息
 * @param {string} id 设备id
 * @param {object} cfg 运行状态信息
 */
function saveAutoRunCfg(id, cfg) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.AUTORUN, id)
  saveData(key, cfg)
}

/**
 * 获取运行状态信息
 * @param {string} id 设备id
 */
function getAutoRunCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.AUTORUN, id)
  const data = getData(key, true, {})
  return data
}
/**
 * 备份设备配置
 * @param {string} id 设备id
 */
function genBackupData(id) {
  const backupData = {}
  const keys = []
  STORAGE_SAVE_KEYS.forEach(key => {
    keys.push(getStorageKey(key, id))
  })
  const arr = wx.batchGetStorageSync(keys)
  for (let i = 0; i < STORAGE_SAVE_KEYS.length; i++) {
    if (arr[i] != null && arr[i] != "") {
      backupData[STORAGE_SAVE_KEYS[i]] = arr[i]
    }
  }
  return backupData
}

/**
 * 还原备份的配置
 * @param {string} id 设备id
 * @param {object} backupData 备份的数据
 */
function restoreBackupData(id, backupData) {
  for (const key in backupData) {
    const newKey = getStorageKey(key, id)
    wx.setStorageSync(newKey, backupData[key])
  }
}

/**
 * 备份所有设备配置
 */
function genBackupAllData() {
  const ids = getDeviceIds()
  const devices = batchGetDeviceInfo(ids)
  const gdevices = getGroups()
  const allDevices = [...devices, ...gdevices]
  const dataArr = []
  allDevices.forEach(device => {
    const backupData = {}
    const keys = []
    STORAGE_SAVE_KEYS.forEach(key => {
      if (key != "device") {
        keys.push(getStorageKey(key, device.deviceId))
      } else {
        keys.push("key_device_xxxxxxxxx")
      }
    })
    const arr = wx.batchGetStorageSync(keys)
    for (let i = 0; i < STORAGE_SAVE_KEYS.length; i++) {
      if (arr[i] != null && arr[i] != "") {
        backupData["key_" + STORAGE_SAVE_KEYS[i] + "_"] = arr[i]
      }
    }
    backupData["key_device_"] = device
    backupData["id"] = device.deviceId
    dataArr.push(backupData)
  })
  return dataArr
}

/**
 * 还原所有备份的配置
 * @param {object} backupData 备份的数据
 */
function restoreBackupAllData(dataArr) {
  const deviceIds = getDeviceIds()
  const gdeviceIds = getGroupIds()
  for (var i = 0; i < dataArr.length; i++) {
    const obj = dataArr[i];
    const id = obj.id;
    const isGroup = id.startsWith("group")
    let isContain = false;
    if (isGroup) {
      for (var j = 0; j < gdeviceIds.length; j++) {
        if (id == gdeviceIds[j]) {
          isContain = true;
          break;
        }
      }
      if (!isContain) {
        gdeviceIds.push(id);
      }
    } else {
      for (var j = 0; j < deviceIds.length; j++) {
        if (id == deviceIds[j]) {
          isContain = true;
          break;
        }
      }
      if (!isContain) {
        deviceIds.push(id);
      }
    }

    STORAGE_SAVE_KEYS.forEach(key => {
      if (key != "device") {
        const bakKey = "key_" + key + "_"
        const relKey = bakKey + id
        if (obj[bakKey] != null) {
          wx.setStorageSync(relKey, obj[bakKey])
        }
      }
    })
    wx.setStorageSync('key_device_' + id, obj['key_device_'])
  }
  saveDeviceIds(deviceIds)
  saveGroupIds(gdeviceIds)
}

/**
 * 保存设备配置列表
 * @param {string} id 设备id
 * @param {array} configsList 配置列表
 */
function saveConfigList(id, configsList) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.SAVED_CONFIGS, id)
  saveData(key, configsList)
}

/**
 * 获取设备配置列表
 * @param {string} id 设备id
 */
function getConfigList(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.SAVED_CONFIGS, id)
  return getData(key, true, [])
}

/**
 * 删除设备缓存
 * @param {string} id 
 */
function removeDevice(id) {
  const keyIds = getStorageKey(STORAGE_KEYS.DEVICEIDS)
  const ids = getData(keyIds, true, [])
  const newIds = []
  ids.forEach(ele => {
    if (ele !== id) {
      newIds.push(ele)
    }
  })
  saveData(keyIds, newIds)

  STORAGE_DEL_KEYS.forEach(ele => {
    const key = getStorageKey(ele, id)
    wx.removeStorageSync(key)
  })
}

/**
 * 设置首页设备列表刷新标志
 */
function setRefreshDevicesFlag() {
  const key = getStorageKey(STORAGE_KEYS.REFRESH_DEVICED_FLAG)
  saveData(key, true)
}

/**
 * 删除首页设备列表刷新标志
 */
function getRefreshDevicesFlag() {
  const key = getStorageKey(STORAGE_KEYS.REFRESH_DEVICED_FLAG)
  const flag = getData(key, false, false)
  if (flag) {
    wx.removeStorageSync(key)
  }
  return flag
}

/**
 * 获取设备组id列表
 * @returns {Array} 设备列表
 */
function getGroupIds() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.GROUPIDS)
  const groupIds = getData(key, true, [])
  return groupIds
}

/**
 * 保存设备组id列表
 */
function saveGroupIds(ids) {
  const key = getStorageKey(STORAGE_KEYS.GROUPIDS)
  saveData(key, ids)
}

/**
 * 保存自由模式信息
 * @param {string} id 设备id
 * @param {object} cfg 运行状态信息
 */
function saveAutoCfg(id, cfg) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.AUTO, id)
  saveData(key, cfg)
}

/**
 * 获取自由模式信息
 * @param {string} id 设备id
 */
function getAutoCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.AUTO, id)
  const data = getData(key, true, {})
  return data
}

/**
 * 删除自由模式信息
 * @param {string} id 设备id
 */
function removeAutoCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.AUTO, id)
  wx.removeStorageSync(key)
}

/**
 * 保存手动模式信息
 * @param {string} id 设备id
 * @param {object} cfg 运行状态信息
 */
function saveHandCfg(id, cfg) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.HAND, id)
  saveData(key, cfg)
}

/**
 * 获取手动模式信息
 * @param {string} id 设备id
 */
function getHandCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.HAND, id)
  const data = getData(key, true, {})
  return data
}

/**
 * 删除手动模式信息
 * @param {string} id 设备id
 */
function removeHandCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.HAND, id)
  wx.removeStorageSync(key)
}

/**
 * 保存日出日落模式信息
 * @param {string} id 设备id
 * @param {object} cfg 运行状态信息
 */
function saveUpdownCfg(id, cfg) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.UPDOWN, id)
  saveData(key, cfg)
}

/**
 * 获取日出日落模式信息
 * @param {string} id 设备id
 */
function getUpdownCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.UPDOWN, id)
  const data = getData(key, true, {})
  return data
}

/**
 * 删除日出日落模式信息
 * @param {string} id 设备id
 */
function removeUpdownCfg(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.DEVICE.UPDOWN, id)
  wx.removeStorageSync(key)
}

/**
 * 获取待激活信息
 */
function getActiveIds() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.ACTIVE_IDS)
  const data = getData(key, true, [])
  return data
}

/**
 * 设置待激活信息
 * @param {string} id 设备id
 */
function setActiveIds(id) {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.ACTIVE_IDS)
  const data = getData(key, true, [])
  const now = new Date();
  // 获取时间组件（年、月、日、时、分、秒）
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始需+1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  data.push(`${id}${year}${month}${day}${hours}${minutes}${seconds}`)
  saveData(key, data)
}

/**
 * 设置待激活信息
 */
function removeActiveIds() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.ACTIVE_IDS)
  wx.removeStorageSync(key)
}

/**
 * 获取是否需要显示指引
 */
function getIosGuideShow() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.IOS_GUIDE_SHOW)
  return getData(key, false, 1)
}
/**
 * 设置不需要显示指引
 */
function setIosGuideNotShow() {
  // 构建存储键
  const key = getStorageKey(STORAGE_KEYS.IOS_GUIDE_SHOW)
  return saveData(key, 0)
}

module.exports = {
  // 常量导出
  STORAGE_KEYS,

  // 核心函数
  getStorageKey,
  saveData,
  getData,

  // 获取数据
  getGroups,
  getModeSettingData,
  getShortcutModeData,
  getPlayerModeData,
  getPlayerModePresets,
  getAdvancedModeData,
  getLightModeState,
  getDeviceConfig,

  getDeviceIds,
  getDeviceInfo,
  getDeviceChannels,
  getTempInfo,
  getScheduleInfo,
  getOpenid,
  getSid,
  getAutoRunCfg,
  getConfigList,
  getLastManualVal,
  getRefreshDevicesFlag,
  getGroupIds,
  getTmpSynced,
  getAutoCfg,
  getHandCfg,
  getUpdownCfg,
  getActiveIds,
  getIosGuideShow,

  // 保存数据
  //saveDevices,
  saveModeSettingData,
  saveShortcutModeData,
  savePlayerModeData,
  saveAdvancedModeData,
  saveLightModeState,
  saveDeviceConfig,

  saveLastManualVal,
  saveDeviceIds,
  saveDeviceInfo,
  saveDeviceChannels,
  saveTempInfo,
  saveScheduleInfo,
  saveAutoRunCfg,
  saveConfigList,
  saveGroupIds,
  saveAutoCfg,
  saveHandCfg,
  saveUpdownCfg,

  // 编组同步
  syncDeviceDataFromGroup,
  clearDeviceGroupSyncData,
  restoreDevicesOnGroupDelete,

  // 首次访问标记
  isFirstVisitShortcutMode,
  setShortcutModeVisited,
  isFirstVisitPlayerMode,
  setPlayerModeVisited,
  isManualModeState,

  setTmpSynced,
  setOpenid,
  setSid,
  setRefreshDevicesFlag,
  setActiveIds,
  setIosGuideNotShow,

  //删除
  removeScheduleInfo,
  removeDevice,
  removeAutoCfg,
  removeHandCfg,
  removeUpdownCfg,
  removeActiveIds,

  //备份还原
  genBackupData,
  genBackupAllData,
  restoreBackupData,
  restoreBackupAllData,

  batchGetDeviceInfo,


}